import axios from 'axios';
import { weworkConfig, WEWORK_API } from '../config/wework';
import redisClient from '../config/redis';

export class WeworkService {
  private static instance: WeworkService;
  
  private constructor() {}

  public static getInstance(): WeworkService {
    if (!WeworkService.instance) {
      WeworkService.instance = new WeworkService();
    }
    return WeworkService.instance;
  }

  // 获取访问令牌
  async getAccessToken(): Promise<string> {
    const cacheKey = 'wework:access_token';
    
    // 尝试从Redis获取缓存的token
    const cachedToken = await redisClient.get(cacheKey);
    if (cachedToken) return cachedToken;

    // 如果没有缓存，则从企业微信获取新token
    const response = await axios.get(WEWORK_API.GET_ACCESS_TOKEN, {
      params: {
        corpid: weworkConfig.corpId,
        corpsecret: weworkConfig.secret
      }
    });

    const { access_token, expires_in } = response.data;
    
    // 将token存入Redis，设置过期时间比实际过期时间少100秒
    await redisClient.setEx(cacheKey, expires_in - 100, access_token);
    
    return access_token;
  }

  // 获取用户信息
  async getUserInfo(code: string) {
    const accessToken = await this.getAccessToken();
    
    const response = await axios.get(WEWORK_API.GET_USER_INFO, {
      params: {
        access_token: accessToken,
        code
      }
    });

    const { UserId, DeviceId } = response.data;
    
    // 获取用户详细信息
    if (UserId) {
      const userDetail = await this.getUserDetail(UserId, accessToken);
      return userDetail;
    }

    return null;
  }

  // 获取用户详细信息
  private async getUserDetail(userId: string, accessToken: string) {
    const response = await axios.get(WEWORK_API.GET_USER_DETAIL, {
      params: {
        access_token: accessToken,
        userid: userId
      }
    });

    return response.data;
  }
} 